import { FC, memo, useState } from 'react'
// @ts-ignore
import ReactMarkdown, { Options } from 'react-markdown'
import rehypeMathjax from 'rehype-mathjax'
import remarkGfm from 'remark-gfm'
import remarkMath from 'remark-math'
import rehypeHighlight from 'rehype-highlight'
import 'highlight.js/styles/github-dark.css'
export const MemoizedReactMarkdown: FC<Options> = memo(
  ReactMarkdown,
  (prevProps, nextProps) => prevProps.children === nextProps.children
)

interface MarkdownProps {
  content: string
  inStreaming?: boolean
  pending?: boolean
  className?: string
}

const Markdown: FC<MarkdownProps> = ({
  content,
  inStreaming,
  pending,
  className,
}) => {
  const [showModal, setShowModal] = useState(false) // Modal visibility state
  const [modalImage, setModalImage] = useState('') // Image URL for preview

  // JSX structure for image modal
  const ImageModal = () => (
    <div
      className="fixed top-0 bottom-0 left-0 right-0 z-[9999] flex items-center justify-center bg-black bg-opacity-50"
      style={{ display: showModal ? 'flex' : 'none' }}
      onClick={() => setShowModal(false)}
    >
      <div
        className="relative max-h-full overflow-y-auto max-w-[95%] lg:max-w-[85%]"
        onClick={(event) => event.stopPropagation()} // Prevent event bubbling
      >
        <img src={modalImage} alt="Preview" className="max-w-full" />
      </div>
      <span
        className="absolute m-2 text-white top-10 right-10 text-[36px] cursor-pointer"
        onClick={() => setShowModal(false)}
      >
        ×
      </span>
    </div>
  )

  const copyCode = async (e: React.MouseEvent<HTMLDivElement>) => {
    const dom = e.currentTarget
    const id = dom.id
    const codeId = id.split('-')[1]
    const textToCopy = (document.querySelector(`#${codeId}`) as HTMLElement)!
      .innerText
    try {
      if (!textToCopy) {
        throw new Error('无法复制空内容')
      }

      const textArea = document.createElement('textarea')
      textArea.value = textToCopy

      document.body.appendChild(textArea)
      textArea.select()
      document.execCommand('copy')
      document.body.removeChild(textArea)
      dom.innerText = '已复制'
      let timer = setTimeout(() => {
        clearTimeout(timer)
        dom.innerText = '复制'
      }, 800)
    } catch (error) {
      dom.innerText = '复制出错'
      let timer = setTimeout(() => {
        clearTimeout(timer)
        dom.innerText = '复制'
      }, 1000)
    }
  }

  return (
    <div className={className}>
      <MemoizedReactMarkdown
        remarkPlugins={[remarkGfm, remarkMath]}
        rehypePlugins={[rehypeMathjax, rehypeHighlight]}
        components={{
          // Code block rendering
          code({ node, inline, className, children, ...props }) {
            if (Array.isArray(children) && children.length > 0) {
              if (children[0] === '▍') {
                return (
                  <div className="inline-block">
                    {inStreaming && !pending ? (
                      <span className="mt-1 cursor-default">▍</span>
                    ) : null}
                  </div>
                )
              }

              // children[0] = (children[0] as string).replace('`▍`', '▍')
            }

            const match = /language-(\w+)/.exec(className || '')
            const id = 'a' + Math.random().toString(36).substr(2, 9)
            return !inline && Array.isArray(children) ? (
              <pre
                className={`language-${match?.[1] || 'text'} 
                bg-[#f8f8f8]
              p-4 rounded-md
              text-sm leading-relaxed
              border border-[#e0e0e0] 
            `}
              >
                <div className="flex">
                  <span>{Array.isArray(match) ? match[1] : ''}</span>
                  <div className="flex-1"></div>
                  <div
                    className="text-xs cursor-pointer"
                    id={`btn-${id}`}
                    onClick={copyCode}
                  >
                    复制
                  </div>
                </div>
                <code
                  id={id}
                  className={`${className}  overflow-x-auto custom-scrollbar code-scrollbar`}
                  {...props}
                >
                  {children}
                </code>
              </pre>
            ) : (
              <span
                className="bg-[#0d1117] text-[#83d6ff] p-1 rounded text-xs
"
                {...props}
              >
                {children}
              </span>
            )
          },
          // Table rendering
          table({ children }) {
            return (
              <table className="px-3 py-1 border border-collapse border-black dark:border-white">
                {children}
              </table>
            )
          },
          th({ children }) {
            return (
              <th className="px-3 py-1 text-white break-words bg-gray-500 border border-black dark:border-white">
                {children}
              </th>
            )
          },
          td({ children }) {
            return (
              <td className="px-3 py-1 break-words border border-black dark:border-white">
                {children}
              </td>
            )
          },

          // Other components
          p({ children }) {
            return <>{children}</>
          },
          dl({ children }) {
            const newChildren = Array.isArray(children)
              ? children.filter((item) => item !== '\n')
              : children
            return <dl className="">{newChildren}</dl>
          },
          ol({ children }) {
            const newChildren = Array.isArray(children)
              ? children.filter((item) => item !== '\n')
              : children
            return <ol className="">{newChildren}</ol>
          },
          ul({ children }) {
            const newChildren = Array.isArray(children)
              ? children.filter((item) => item !== '\n')
              : children
            return <ul className="">{newChildren}</ul>
          },
          li({ children }) {
            const newChildren = Array.isArray(children)
              ? children.filter((item) => item !== '\n')
              : children
            return <li>{newChildren}</li>
          },
          a({ children, ...props }) {
            return (
              <>
                {children[0] === '详细' ? null : (
                  <a
                    className="text-blue-500 underline cursor-pointer hover:text-blue-700 "
                    href={props.href}
                    target="_blank"
                    rel="noreferrer"
                  >
                    {children}
                  </a>
                )}
              </>
            )
          },
          img({ src, alt }) {
            return (
              <img
                src={src}
                alt={alt}
                className="max-w-full h-auto lg:max-w-[800px] cursor-zoom-in pt-5 pb-5"
                onClick={(event) => {
                  event.preventDefault()
                  setModalImage(src!)
                  setShowModal(true)
                }}
              />
            )
          },
        }}
      >
        {content}
      </MemoizedReactMarkdown>
      <ImageModal /> {/* Render image preview modal */}
    </div>
  )
}

export default Markdown
